import React, {Component} from "react";

import PageList from '../page-list/index';
import {SHOW_ALL_DATA} from "../page-list/type";
import connect from "react-redux/es/connect/connect";
import {Rect, Stage, Layer, Transformer} from "react-konva"

class TransformerComponent extends React.Component {
    componentDidMount() {
        this.checkNode();
    }

    componentDidUpdate() {
        this.checkNode();
    }

    checkNode() {
        const stage = this.transformer.getStage();
        const {selectedShapeName} = this.props;
        const selectedNode = stage.findOne('.' + selectedShapeName);
        if (selectedNode === this.transformer.node()) {
            return;
        }
        if (selectedNode) {
            this.transformer.attachTo(selectedNode);
        } else {
            this.transformer.detach();
        }
        this.transformer.getLayer().batchDraw();
    }

    render() {
        return (
            <Transformer
                ref={node => {
                    this.transformer = node;
                }}
            />
        );
    }
}

class Graphics extends Component {
    state = {
        x: 20,
        y: 20,
        width: 100,
        height: 100,
        selectedShapeName: ''
    };

    handleStageMouseDown(e) {
        if (e.target === e.target.getStage()) {
            this.setState({
                selectedShapeName: ''
            });
            return;
        }
        const clickedOnTransformer =
            e.target.getParent().className === 'Transformer';
        if (clickedOnTransformer) {
            return;
        }
        this.setState({
            selectedShapeName: e.target.name()
        });
    };

    render() {
        const {x, y, width, height} = this.state;
        return (
            <Stage
                width={window.innerWidth}
                height={window.innerHeight}
                onMouseDown={this.handleStageMouseDown.bind(this)}
            >
                <Layer>
                    {/*矩形组件*/}
                    <Rect
                        selectedShapeName=""
                        name='rect1'
                        ref="rect"
                        x={x}
                        y={y}
                        width={width}
                        height={height}
                        stroke='red'
                        strokeWidth={3}
                        draggable={true}
                    />
                    {/*拉伸组件*/}
                    <TransformerComponent
                        selectedShapeName={this.state.selectedShapeName}
                    />
                </Layer>
            </Stage>
        );
    }
}

const mapStateToProps = state => {
    return {
        result: state.result
    };
};


Graphics = connect(
    mapStateToProps,
    null
)(Graphics);
export default Graphics;